package com.lyl.xxx.modules.framework.security.model.details;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.lyl.xxx.modules.system.account.entity.SysUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Mr.Luo
 * @date 2022-09-19 11:19
 * @desc
 */
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
public class LoginDetails implements UserDetails {
    private SysUser sysUser;
    /**
     * token
     */
    private String token;
    /**
     * 登录时间
     */
    private long loginTime;
    /**
     * 过期时间
     */
    private long expireTime;

    /**
     * 登录地址
     */
    private String loginAddress;

    /**
     * 操作系统
     */
    private String os;

    /**
     * 浏览器
     */
    private String browser;

    private Set<String> perms;

    public LoginDetails(SysUser sysUser, Set<String> perms) {
        this.sysUser = sysUser;
        this.perms = perms;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return CollUtil.emptyIfNull(perms.stream()
                .filter(CharSequenceUtil::isNotBlank)
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet()));
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
